package com.ankiang.mykeys;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.ankiang.mykeys.common.Constant;
import com.ankiang.utils.DBManager;
import com.ankiang.utils.HttpUtil;
import com.etsy.android.grid.StaggeredGridView;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by KavenFan on 2017/4/12.
 */

public class FragmentHome extends Fragment implements
        AbsListView.OnScrollListener, AbsListView.OnItemClickListener {

    // 本地缓存数据，SQLLite
    DBManager dbManager;

    TextView textView;
    public final String TAG = "Home";

    // 瀑布流
    private StaggeredGridView mGridView;

    // 是否还有数据
    private boolean mHasRequestedMore;

    // 软件适配器
    private AppAdapter mAdapter;

    // 收到的数据
    private JSONArray mData;

    // 每次显示的数量
    public final int APP_SHOW_COUNT = 20;

    // 当前最后一个数据的ID
    private int current = 0;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.home, null);
        textView = (TextView) view.findViewById(R.id.homeText);
        dbManager = new DBManager(view.getContext());
        init(savedInstanceState);
        return view;
    }


    void init(final Bundle savedInstanceState) {
        Log.i(TAG, "http asyn...");
        int start = 0;
        int count = APP_SHOW_COUNT;
        String urlFormat="http://mykeys.sinaapp.com/ifc/getAppList.php?start=%d&count=%d";
        String urlString = String.format(urlFormat, start, count); // 一個獲取菜谱的url地址
        String key = Constant.K_APP_ALL;
        String json = dbManager.get(key);

        dbManager.update(Constant.K_CURRENT_DATA, key); // 保存当前数据是哪个

        if ("".equals(json)) {
            Log.i(TAG, "using http");
            HttpUtil.get(urlString, new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) { // 获取数据成功会调用这里
                    if (response != null) {
                        String s = response.toString();
                        textView.setText(s);
                        dbManager.update(Constant.K_APP_ALL, s);
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    if (response != null) {
                        Log.i(TAG, "http asyn onSuccess JSONObject...");
                        try {
                            JSONObject res = (JSONObject) response.get("res");
                            int code = res.getInt("code");
                            if (code != 0) {
                                String msg = res.getString("msg");
                                Toast.makeText(getActivity(), "Error: " + msg, Toast.LENGTH_LONG).show();
                                return;
                            }
                            mData = response.getJSONArray("data");


                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();

                        }
                        String s = response.toString();

                        dbManager.update(Constant.K_APP_ALL, s);
                        initViews(savedInstanceState);

                        //textView.setText(s);
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { // 失败，调用
                    if (throwable != null) {
                        textView.setText(throwable.getMessage());
                    }
                }

                public void onFinish() { // 完成后调用，失败，成功，都要掉
                    super.onFinish();
                    Log.i(TAG, "http asyn onFinish");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    if (throwable != null) {
                        textView.setText(throwable.getMessage());
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    if (throwable != null) {
                        textView.setText(throwable.getMessage());
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    textView.setText(responseString);
                }

            });
        } else {
            Log.i(TAG, "using cached data");
            try {
                JSONObject response = new JSONObject(json);
                JSONObject res = (JSONObject) response.get("res");
                int code = res.getInt("code");
                if (code != 0) {
                    String msg = res.getString("msg");
                    Toast.makeText(getActivity(), "Error: " + msg, Toast.LENGTH_LONG).show();
                    return;
                }
                mData = response.getJSONArray("data");


            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();

            }
        }

    }

    void initViews(final Bundle savedInstanceState){

        mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);

        if (savedInstanceState == null) {
            final LayoutInflater layoutInflater = getActivity().getLayoutInflater();

            View header = layoutInflater.inflate(R.layout.home_list_item_header_footer, null);
            View footer = layoutInflater.inflate(R.layout.home_list_item_header_footer, null);
            TextView txtHeaderTitle = (TextView) header.findViewById(R.id.txt_title);
            TextView txtFooterTitle = (TextView) footer.findViewById(R.id.txt_title);
            txtHeaderTitle.setText("THE HEADER!");
            txtFooterTitle.setText("THE FOOTER!");

            mGridView.addHeaderView(header);
            mGridView.addFooterView(footer);
        }

        if (mAdapter == null) {
            mAdapter = new AppAdapter(getActivity(), R.id.app_des);
        }

        if (mData == null) {
            mData = new JSONArray();
        }

        for (int i = 0; i + current < mData.length() && i < APP_SHOW_COUNT; i++) {
            JSONObject data;
            try {
                data = mData.getJSONObject(i + current);
                mAdapter.add(data);
                current++;
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG);
                break;
            }
        }

        mGridView.setAdapter(mAdapter);
        mGridView.setOnScrollListener(this);
        mGridView.setOnItemClickListener(this);
    }

    @Override
    public void onActivityCreated(final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews(savedInstanceState);
    }

    @Override
    public void onScrollStateChanged(final AbsListView view, final int scrollState) {
        Log.d(TAG, "onScrollStateChanged:" + scrollState);
    }

    @Override
    public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
        Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem +
                " visibleItemCount:" + visibleItemCount +
                " totalItemCount:" + totalItemCount);
        // our handling
        if (!mHasRequestedMore) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen >= totalItemCount) {
                Log.d(TAG, "onScroll lastInScreen - so load more");
                mHasRequestedMore = true;
                onLoadMoreItems();
            }
        }
    }

    private void onLoadMoreItems() {

        for (int i = 0; i + current < mData.length() && i < APP_SHOW_COUNT; i++) {
            JSONObject data;
            try {
                data = mData.getJSONObject(i + current);
                mAdapter.add(data);
                current++;
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG);
                break;
            }
        }
        // notify the adapter that we can update now
        mAdapter.notifyDataSetChanged();
        mHasRequestedMore = false;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        AppAdapter.ViewHolder vh = (AppAdapter.ViewHolder)view.getTag();
        //String s = vh.txtAppDes.getText().toString();
        //Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();

        String appId = vh.appId;
        Intent intent = new Intent();
        intent.setClass(getContext(), ShortcutActivity.class);
        Log.i("AppId", appId);

        intent.putExtra("appId", appId);

        startActivity(intent);
    }

}
